using UnityEngine;
using System.Collections;
using UnityEngine.UI;

/// <summary>
/// Battle场景的自动设置脚本
/// 确保所有必要组件都存在并正确配置
/// </summary>
public class BattleSceneSetup : MonoBehaviour
{
    [Header("核心组件")]
    [SerializeField] private bool ensureWordDatabase = true;
    [SerializeField] private bool ensureUIManager = true;
    [SerializeField] private bool checkComponentReferences = true;
    
    [Header("调试设置")]
    [SerializeField] private bool verboseLogging = true;
    
    private void Awake()
    {
        Debug.Log("[BattleSceneSetup] 战斗场景初始化开始...");
    }
    
    private IEnumerator Start()
    {
        // 等待一帧以确保其他组件已初始化
        yield return null;
        
        // 确保WordDatabase存在
        if (ensureWordDatabase)
        {
            EnsureWordDatabaseExists();
        }
        
        // 确保UIManager存在
        if (ensureUIManager)
        {
            EnsureUIManagerExists();
        }
        
        // 检查并修复组件引用
        if (checkComponentReferences)
        {
            yield return StartCoroutine(CheckAndFixComponentReferences());
        }
        
        Debug.Log("[BattleSceneSetup] 战斗场景初始化完成");
    }
    
    /// <summary>
    /// 确保WordDatabase存在
    /// </summary>
    private void EnsureWordDatabaseExists()
    {
        if (WordDatabase.Instance == null)
        {
            Debug.LogWarning("[BattleSceneSetup] 未找到WordDatabase实例，创建一个新实例");
            GameObject wordDBObject = new GameObject("WordDatabase");
            wordDBObject.AddComponent<WordDatabase>();
            DontDestroyOnLoad(wordDBObject);
        }
        else if (verboseLogging)
        {
            Debug.Log("[BattleSceneSetup] WordDatabase实例已存在");
        }
    }
    
    /// <summary>
    /// 确保UIManager存在
    /// </summary>
    private void EnsureUIManagerExists()
    {
        UIManager uiManager = FindObjectOfType<UIManager>();
        if (uiManager == null)
        {
            Debug.LogWarning("[BattleSceneSetup] 未找到UIManager实例，创建一个新实例");
            GameObject uiManagerObject = new GameObject("UIManager");
            uiManagerObject.AddComponent<UIManager>();
        }
        else if (verboseLogging)
        {
            Debug.Log("[BattleSceneSetup] UIManager实例已存在");
        }
    }
    
    /// <summary>
    /// 检查并修复组件引用
    /// </summary>
    private IEnumerator CheckAndFixComponentReferences()
    {
        Debug.Log("[BattleSceneSetup] 检查组件引用...");
        
        // 查找InputManager并确保它的文本引用正确
        InputManager[] inputManagers = FindObjectsOfType<InputManager>();
        
        if (inputManagers.Length == 0)
        {
            Debug.LogError("[BattleSceneSetup] 场景中没有InputManager！");
        }
        else
        {
            foreach (InputManager im in inputManagers)
            {
                if (im.wordDisplay == null)
                {
                    Debug.LogWarning($"[BattleSceneSetup] InputManager '{im.name}' 的wordDisplay引用丢失，尝试查找替代");
                    
                    // 查找可能的wordDisplay文本组件
                    Text[] allTexts = FindObjectsOfType<Text>();
                    foreach (Text text in allTexts)
                    {
                        if (text.name.Contains("Word") || text.name.Contains("单词") || 
                            text.text == "NewText" || text.text.Length == 0)
                        {
                            im.wordDisplay = text;
                            Debug.Log($"[BattleSceneSetup] 已将 '{text.name}' 设置为 '{im.name}' 的wordDisplay");
                            break;
                        }
                    }
                }
                
                if (im.chineseDisplay == null)
                {
                    Debug.LogWarning($"[BattleSceneSetup] InputManager '{im.name}' 的chineseDisplay引用丢失，尝试查找替代");
                    
                    // 查找可能的chineseDisplay文本组件
                    Text[] allTexts = FindObjectsOfType<Text>();
                    foreach (Text text in allTexts)
                    {
                        if (text.name.Contains("Chinese") || text.name.Contains("中文") || 
                            text.name.Contains("Meaning") || text.name.Contains("意思"))
                        {
                            im.chineseDisplay = text;
                            Debug.Log($"[BattleSceneSetup] 已将 '{text.name}' 设置为 '{im.name}' 的chineseDisplay");
                            break;
                        }
                    }
                }
            }
        }
        
        // 尝试修复所有显示"NewText"的文本组件
        Text[] texts = FindObjectsOfType<Text>();
        int fixedCount = 0;
        
        foreach (Text text in texts)
        {
            if (text.text == "NewText" || text.text.Length == 0)
            {
                // 立即更新一次词汇显示
                InputManager[] ims = FindObjectsOfType<InputManager>();
                if (ims.Length > 0)
                {
                    ims[0].LoadNewWord();
                    fixedCount++;
                    
                    Debug.Log($"[BattleSceneSetup] 尝试修复显示'NewText'的文本组件: {text.name}");
                    
                    // 等待一帧以确保更新生效
                    yield return null;
                }
            }
        }
        
        Debug.Log($"[BattleSceneSetup] 组件引用检查完成，尝试修复了 {fixedCount} 个NewText问题");
    }
} 